/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel.di;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 类型标志，每个类型标志可映射一个实例提供者{@link cn.webwheel.di.Provider}。
 */
@SuppressWarnings("unchecked")
final public class Key<T> {

    private Class<T> cls;
    private Type type;
    private String name;

    /**
     * 唯一的构造方法。
     * @param type 类型标志，目前只支持{@link Class}和{@link java.lang.reflect.ParameterizedType}两种类型。
     * @param name 注入静态参数
     */
    public Key(Type type, String name) {
        if (type == null || name == null) throw new IllegalArgumentException("type or name can not be null");
        if (type instanceof Class) {
            cls = (Class<T>) type;
        } else if (type instanceof ParameterizedType) {
            cls = (Class<T>) ((ParameterizedType) type).getRawType();
        } else {
            throw new IllegalArgumentException("only support class or paramerterized type");
        }
        this.type = type;
        this.name = name;
    }

    /**
     * 获得类型
     * @return 类型
     */
    public Type getType() {
        return type;
    }

    /**
     * 获得标志名称
     * @return 标志名称
     */
    public String getName() {
        return name;
    }

    /**
     * 获得类型对应的类对象
     * @return 类对象
     */
    public Class<T> toClass() {
        return cls;
    }

    @Override
    public String toString() {
        return "Key{" +
                "type=" + type +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Key key = (Key) o;

        if (!name.equals(key.name)) return false;
        if (!type.equals(key.type)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = type.hashCode();
        result = 31 * result + name.hashCode();
        return result;
    }
}
